import { useEffect, useRef } from "react";
import styles from "./index.module.less";
import AMapLoader from "@amap/amap-jsapi-loader";
import { PolygonData, MarkerData, PolylineData } from "./constants";

interface Props {
	title?: string;
	defaultValues?: any;
	mapStyle?: string;
	polygons?: PolygonData[]; // 多边形数据参数
	markers?: MarkerData[]; // Array of marker data
	defaultIcon?: string; // Default icon URL if marker doesn't specify one
	hoverStyle?: {
		className?: string;
		content?: string;
		offset?: [number, number];
	};
	polylinePaths?: PolylineData[]; // 支持多条路径
	realTimeMaker?: MarkerData; // 单个实时标记（向后兼容）
	realTimeMarkers?: MarkerData[]; // 多个实时标记
	pathColor?: string; // 保持向后兼容
}

export default function MapContainer(props: Props) {
	const {
		mapStyle,
		polygons = [],
		markers = [],
		defaultIcon = "/images/icon-joint.png",
		polylinePaths = [],
		realTimeMaker,
		realTimeMarkers = [],
		pathColor = "#00847C"
	} = props;
	const mapRef = useRef<any>(null); // 使用 useRef 来保存 map 实例
	const polygonsRef = useRef<any[]>([]); // 保存当前绘制的多边形实例
	const markersRef = useRef<any[]>([]); //保存当前绘制的点位
	const realTimeRef = useRef<any>(null); // 单个实时标记（向后兼容）
	const realTimeMarkersRef = useRef<any[]>([]); // 多个实时标记
	const polylinesRef = useRef<any[]>([]); // 保存当前绘制的折线实例
	const infoWindowRef = useRef<any>(null); // 保存信息窗口实例
	const markerInfoWindowRef = useRef<any>(null); // 保存标记信息窗口实例

	useEffect(() => {
		(window as any)._AMapSecurityConfig = {
			securityJsCode: "1a4a93802981d6152825c7f03277b109"
		};
		AMapLoader.load({
			key: "a1ebd3dc42c785dc8ff903f2280490f5", // 申请好的Web端开发者Key，首次调用 load 时必填
			version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ["AMap.Polygon"] // 需要使用的的插件列表
		})
			.then(AMap => {
				mapRef.current = new AMap.Map("container", {
					// 设置地图容器id
					viewMode: "3D", // 是否为3D地图模式
					zoom: 11, // 初始化地图级别
					mapStyle: "amap://styles/" + mapStyle,
					center: [120, 31] // 初始化地图中心点位置
				});

				if (realTimeMaker) {
					createRealTimeMaker(AMap);
				}

				if (realTimeMarkers && realTimeMarkers.length > 0) {
					createRealTimeMarkers(AMap);
				}

				if (markers && markers.length > 0) {
					addMarkers(AMap);
				}
				// 初始化地图后绘制多边形
				drawPolygons(AMap, polygons);
				// 如果有初始路径，创建折线
				if (polylinePaths.length > 0) {
					createPolylines(AMap);
				}
			})
			.catch(e => {
				console.log(e);
			});

		return () => {
			// 清除所有多边形
			clearMarkers();
			clearPolygons();
			clearPolylines();
			clearRealTimeMarkers();
			clearRealTimeMarkersArray();
			mapRef.current?.destroy();
		};
	}, []);

	//监听 实时点位 变化
	useEffect(() => {
		if (mapRef.current && (window as any).AMap && realTimeMaker) {
			createRealTimeMaker((window as any).AMap);
		}
	}, [realTimeMaker]);

	//监听 多个实时点位 变化
	useEffect(() => {
		if (mapRef.current && (window as any).AMap && realTimeMarkers.length > 0) {
			createRealTimeMarkers((window as any).AMap);
		}
	}, [realTimeMarkers]);

	// 监听折线路径变化
	useEffect(() => {
		if (mapRef.current && (window as any).AMap && polylinePaths.length > 0) {
			// 清除旧折线
			clearPolylines();
			// 创建新折线
			createPolylines((window as any).AMap);
			// 自动调整视图适应所有折线
			if (polylinesRef.current.length > 0) {
				mapRef.current.setFitView(polylinesRef.current);
			}
		}
	}, [polylinePaths]);

	// 监听 polygons 变化
	useEffect(() => {
		if (mapRef.current && polygons) {
			// 清除旧的多边形
			clearPolygons();
			// 绘制新的多边形
			drawPolygons((window as any).AMap, polygons);
		}
	}, [polygons]);

	//监听 点位 变化
	useEffect(() => {
		if (mapRef.current && (window as any).AMap) {
			clearMarkers();
			addMarkers((window as any).AMap);
		}
	}, [markers]);

	//创建实时点位
	const createRealTimeMaker = (AMap: any) => {
		if (!mapRef.current || !realTimeMaker) return;

		// 如果标记已存在，只更新位置和属性，避免重新创建
		if (realTimeRef.current) {
			const currentPosition = realTimeRef.current.getPosition();
			const newPosition = realTimeMaker.position;

			// 检查位置是否真的发生了变化
			if (currentPosition && newPosition) {
				const currentLng = currentPosition.getLng();
				const currentLat = currentPosition.getLat();
				const newLng = newPosition[0];
				const newLat = newPosition[1];

				// 如果位置有变化，使用panTo平滑移动
				if (Math.abs(currentLng - newLng) > 0.0001 || Math.abs(currentLat - newLat) > 0.0001) {
					realTimeRef.current.setPosition(newPosition);
					// 使用panTo平滑移动地图中心到新位置
					mapRef.current.panTo(newPosition);
				}
			} else {
				// 如果没有当前位置，直接设置新位置
				realTimeRef.current.setPosition(newPosition);
				mapRef.current.panTo(newPosition);
			}

			// 更新其他属性（角度、图标等）
			if (realTimeMaker.angle !== undefined) {
				realTimeRef.current.setAngle(realTimeMaker.angle);
			}
			if (realTimeMaker.icon) {
				realTimeRef.current.setIcon(realTimeMaker.icon);
			}
			if (realTimeMaker.title) {
				realTimeRef.current.setTitle(realTimeMaker.title);
			}
		} else {
			// 首次创建标记
			const { position, title, icon, angle, vehicleInfo, onHover, onLeave, ...otherProps } = realTimeMaker;
			realTimeRef.current = new AMap.Marker({
				position: position,
				title: title || "实时点位",
				icon: icon,
				offset: new AMap.Pixel(-13, -30),
				angle: angle,
				...otherProps
			});

			// 添加鼠标悬浮事件和信息窗口
			if (vehicleInfo && onHover) {
				realTimeRef.current.on("mouseover", () => {
					onHover(vehicleInfo);
				});

				realTimeRef.current.on("mouseout", () => {
					if (onLeave) {
						onLeave();
					}
				});
			}

			// 处理信息窗口
			if (realTimeMaker.infoWindow) {
				const {
					content,
					showOnHover = true,
					showOnClick = false,
					offset = [0, -30],
					closeWhenClickMap = true
				} = realTimeMaker.infoWindow;

				if (content) {
					// 鼠标悬浮显示信息窗口
					if (showOnHover) {
						realTimeRef.current.on("mouseover", () => {
							if (infoWindowRef.current) {
								infoWindowRef.current.close();
							}

							infoWindowRef.current = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							infoWindowRef.current.open(mapRef.current, realTimeRef.current.getPosition());
						});

						realTimeRef.current.on("mouseout", () => {
							// 延迟关闭信息窗口，避免鼠标移动到信息窗口时立即关闭
							setTimeout(() => {
								if (infoWindowRef.current) {
									infoWindowRef.current.close();
								}
							}, 200);
						});
					}

					// 点击显示信息窗口
					if (showOnClick) {
						realTimeRef.current.on("click", () => {
							if (infoWindowRef.current) {
								infoWindowRef.current.close();
							}

							infoWindowRef.current = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							infoWindowRef.current.open(mapRef.current, realTimeRef.current.getPosition());
						});
					}
				}
			}

			mapRef.current.add(realTimeRef.current);
			// 首次创建时设置地图视野
			if (realTimeRef.current) {
				mapRef.current.setFitView(realTimeRef.current);
			}
		}
	};

	// 创建多个实时标记
	const createRealTimeMarkers = (AMap: any) => {
		if (!mapRef.current || !realTimeMarkers.length) return;

		// 清除旧的多个实时标记
		clearRealTimeMarkersArray();

		realTimeMarkersRef.current = realTimeMarkers.map(markerData => {
			const { position, title, icon, angle, vehicleInfo, onHover, onLeave, infoWindow, ...otherProps } = markerData;

			// 创建标记
			const marker = new AMap.Marker({
				position: position,
				title: title || "实时点位",
				icon: icon,
				offset: new AMap.Pixel(-13, -30),
				angle: angle || 0,
				...otherProps
			});

			// 添加鼠标悬浮事件和信息窗口
			if (vehicleInfo && onHover) {
				marker.on("mouseover", () => {
					onHover(vehicleInfo);
				});

				marker.on("mouseout", () => {
					if (onLeave) {
						onLeave();
					}
				});
			}

			// 处理信息窗口
			if (infoWindow) {
				const { content, showOnHover = true, showOnClick = false, offset = [0, -30], closeWhenClickMap = true } = infoWindow;

				if (content) {
					// 鼠标悬浮显示信息窗口
					if (showOnHover) {
						marker.on("mouseover", () => {
							// 关闭其他信息窗口
							realTimeMarkersRef.current.forEach(m => {
								if (m.infoWindow && m.infoWindow !== marker) {
									m.infoWindow.close();
								}
							});

							marker.infoWindow = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							marker.infoWindow.open(mapRef.current, marker.getPosition());
						});

						marker.on("mouseout", () => {
							// 延迟关闭信息窗口，避免鼠标移动到信息窗口时立即关闭
							setTimeout(() => {
								if (marker.infoWindow) {
									marker.infoWindow.close();
								}
							}, 200);
						});
					}

					// 点击显示信息窗口
					if (showOnClick) {
						marker.on("click", () => {
							// 关闭其他信息窗口
							realTimeMarkersRef.current.forEach(m => {
								if (m.infoWindow && m.infoWindow !== marker) {
									m.infoWindow.close();
								}
							});

							marker.infoWindow = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							marker.infoWindow.open(mapRef.current, marker.getPosition());
						});
					}
				}
			}

			mapRef.current.add(marker);
			return marker;
		});

		// 自动调整视图适应所有标记
		if (realTimeMarkersRef.current.length > 0) {
			mapRef.current.setFitView(realTimeMarkersRef.current);
		}
	};

	// 创建多条折线
	const createPolylines = (AMap: any) => {
		if (!mapRef.current || !polylinePaths.length) return;

		// 清除旧折线
		clearPolylines();

		// 为每条路径创建折线
		polylinesRef.current = polylinePaths.map(polylineData => {
			// 合并默认样式和自定义样式
			const options: any = {
				path: polylineData.path,
				strokeColor: polylineData.strokeColor || pathColor, // 线颜色
				strokeWeight: polylineData.strokeWeight || 10, // 线宽
				strokeStyle: polylineData.strokeStyle || "solid", // 线样式
				showDir: polylineData.showDir !== undefined ? polylineData.showDir : true // 显示方向箭头
			};

			// 创建折线实例
			const polyline = new AMap.Polyline(options);

			// 添加到地图
			mapRef.current.add(polyline);

			return polyline;
		});
	};

	const addMarkers = (AMap: any) => {
		if (!mapRef.current || !markers.length) return;

		markersRef.current = markers.map(markerData => {
			// Create custom icon if provided
			let icon: any = undefined;
			if (markerData.icon || defaultIcon) {
				icon = new AMap.Icon({
					image: markerData.icon || defaultIcon,
					size: new AMap.Size(58, 58), // icon size
					imageSize: new AMap.Size(58, 58) // actual image size
				});
			}
			// Create marker
			const marker = new AMap.Marker({
				position: markerData.position,
				title: markerData.title,
				icon: icon,
				map: mapRef.current,
				offset: new AMap.Pixel(-22, -50)
			});

			// 处理标记信息窗口
			if (markerData.infoWindow && markerData.markerInfo) {
				const {
					content,
					showOnHover = true,
					showOnClick = false,
					offset = [0, -30],
					closeWhenClickMap = true
				} = markerData.infoWindow;

				if (content) {
					// 鼠标悬浮显示信息窗口
					if (showOnHover) {
						marker.on("mouseover", () => {
							if (markerInfoWindowRef.current) {
								markerInfoWindowRef.current.close();
							}

							markerInfoWindowRef.current = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							markerInfoWindowRef.current.open(mapRef.current, marker.getPosition());
						});

						marker.on("mouseout", () => {
							// 延迟关闭信息窗口，避免鼠标移动到信息窗口时立即关闭
							setTimeout(() => {
								if (markerInfoWindowRef.current) {
									markerInfoWindowRef.current.close();
								}
							}, 200);
						});
					}

					// 点击显示信息窗口
					if (showOnClick) {
						marker.on("click", () => {
							if (markerInfoWindowRef.current) {
								markerInfoWindowRef.current.close();
							}

							markerInfoWindowRef.current = new AMap.InfoWindow({
								content: content,
								offset: new AMap.Pixel(offset[0], offset[1]),
								closeWhenClickMap: closeWhenClickMap
							});
							markerInfoWindowRef.current.open(mapRef.current, marker.getPosition());
						});
					}
				}
			}

			return marker;
		});

		if (markersRef.current.length > 0) {
			mapRef.current.setFitView(markersRef.current);
		}
	};

	// 绘制多边形函数
	const drawPolygons = (AMap: any, polygonsData: PolygonData[]) => {
		if (!AMap || !mapRef.current || !polygonsData?.length) return;

		polygonsData.forEach(polygonData => {
			const { path, strokeColor = "#01B2A8", fillColor = "#01B2A8", strokeWeight = 2 } = polygonData;

			// 将点数组转换为 AMap.LngLat 数组
			const lngLatPath = path.map(point => new AMap.LngLat(point[0], point[1]));

			// 创建多边形
			const polygon = new AMap.Polygon({
				path: lngLatPath,
				strokeColor,
				strokeWeight,
				fillColor,
				fillOpacity: 0.4
			});

			// 将多边形添加到地图
			mapRef.current.add(polygon);
			// 保存多边形实例
			polygonsRef.current.push(polygon);

			// 自适应地图视野
			mapRef.current.setFitView([polygon]);
		});
	};

	// 清除所有多边形
	const clearPolygons = () => {
		if (mapRef.current && polygonsRef.current.length) {
			polygonsRef.current.forEach(polygon => {
				mapRef.current.remove(polygon);
			});
			polygonsRef.current = [];
		}
	};

	// 清除所有点位
	const clearMarkers = () => {
		markersRef.current.forEach(marker => {
			marker.setMap(null);
		});
		markersRef.current = [];
		// 清除标记信息窗口
		if (markerInfoWindowRef.current) {
			markerInfoWindowRef.current.close();
			markerInfoWindowRef.current = null;
		}
	};

	// 清除实时点位
	const clearRealTimeMarkers = () => {
		realTimeRef.current?.setMap(null);
		realTimeRef.current = null;
		// 清除信息窗口
		if (infoWindowRef.current) {
			infoWindowRef.current.close();
			infoWindowRef.current = null;
		}
	};

	// 清除多个实时标记
	const clearRealTimeMarkersArray = () => {
		if (realTimeMarkersRef.current.length > 0) {
			realTimeMarkersRef.current.forEach(marker => {
				if (marker.infoWindow) {
					marker.infoWindow.close();
				}
				marker.setMap(null);
			});
			realTimeMarkersRef.current = [];
		}
	};

	// 清除所有折线
	const clearPolylines = () => {
		if (mapRef.current && polylinesRef.current.length) {
			polylinesRef.current.forEach(polyline => {
				mapRef.current.remove(polyline);
			});
			polylinesRef.current = [];
		}
	};

	return <div id="container" className={styles.container} style={{ height: "100%" }}></div>;
}
